'use strict'

const Controller = require('egg').Controller
const CryptoJS = require('crypto-js')
const { encrypt, decrypt } = require('../extend/cryptoData')

const IV = '1234567812345678'
const KEY = '12345678901234567890123456789012'
const DATA = '中文加密解密容易出现乱码'

// 解密方法
function deData(data, key, iv) {
  const dataHexStr = CryptoJS.enc.Hex.parse(data)
  const dataBase64 = CryptoJS.enc.Base64.stringify(dataHexStr)
  const key32 = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(key).toString())
  const iv32 = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(iv).toString())
  const decrypt = CryptoJS.AES.decrypt(dataBase64, key32, { iv: iv32, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
  try {
    const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
    return decryptedStr.toString()
  } catch (error) {
    console.log('解密失败', error)
    const decryptedStr = decrypt.toString()
    return decryptedStr.toString()
  }
}

// 加密方法
function enData(data, key, iv) {
  const md5key = CryptoJS.MD5(key).toString()
  const md5iv = CryptoJS.MD5(iv).toString()
  console.log('md5key', md5key)
  console.log('md5iv', md5iv)
  const key32 = CryptoJS.enc.Utf8.parse(md5key)
  const iv32 = CryptoJS.enc.Utf8.parse(md5iv)
  const encrypted = CryptoJS.AES.encrypt(data, key32, { iv: iv32, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
  const dataBase64 = encrypted.ciphertext.toString()
  return dataBase64
}


class HomeController extends Controller {
  async index() {
    const { ctx } = this

    const miwen = encrypt(DATA, KEY, IV)
    const yuanwen = decrypt(miwen, KEY, IV)

    const miwen2 = enData(DATA, KEY, IV)
    const yuanwen2 = deData(miwen2, KEY, IV)

    ctx.body = {
      name: '首页',
      endata: miwen,
      dedata: yuanwen,
      endata2: miwen2,
      dedata2: yuanwen2
    }
  }
}

module.exports = HomeController
